#coding:utf-8;
"""

Author: River
"""
__author__ = 'River'
__license__ = 'Apache'
__version__ = 'v1.0.0'

import os
import json
import time
import pickle
import logging
import requests
import os

from bottle import Bottle, ServerAdapter, request
from bottle import run, debug, route, error, static_file, template

#致命错误日志收集
logging.basicConfig(level=logging.CRITICAL)
_handler = logging.StreamHandler()
_formatter = logging.Formatter("[%(levelname)s]%(asctime)s:%(name)s(%(lineno)s): %(message)s"
                #, datefmt='%Y.%m.%d %H:%M:%S'
                , datefmt='%H:%M:%S'
                )

_handler.setFormatter(_formatter)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.propagate = False
logger.addHandler(_handler)

# 是否运行在正式环境
PROG = os.path.basename(__file__)
IN_PROD = (PROG == 'webhook.py')
ROBOT_URL = IN_PROD and 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<k2>' or 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<k1>'
PORT = IN_PROD and 10000 or 9090

import pprint
pp = pprint.PrettyPrinter(indent=4)

######### Robot Message ################
def send_message_to_robot(msg):
    if msg:
      r = requests.post(ROBOT_URL, (bytes(json.dumps({'msgtype': 'text', 'text': {'content': msg}}), 'utf-8')))
      print(r.status_code, r.reason)
      print(r.text)

######### QPYTHON WEB SERVER ###############
class MyWSGIRefServer(ServerAdapter):
    server = None
    def run(self, handler):
        from wsgiref.simple_server import make_server, WSGIRequestHandler
        if self.quiet:
            class QuietHandler(WSGIRequestHandler):
                def log_request(*args, **kw): pass
            self.options['handler_class'] = QuietHandler
        self.server = make_server(self.host, self.port, handler, **self.options)
        self.server.serve_forever()

    def stop(self):
        import threading
        threading.Thread(target=self.server.shutdown).start()
        self.server.server_close()

######### BUILT-IN ROUTERS ###############
def __exit():
    global server
    server.stop()

def server_static(filepath):
    return static_file(filepath, root='./')


######### WEBAPP ROUTERS WRITE YOUR CODE BELOW###############
def run_start():
    comm = request.forms.get('comm')
    return {"response":'200', "text": comm }

def webhook():
    json_data = request.json

    msg = ''
    if json_data['object_kind'] == 'merge_request':
      pass

    elif json_data['object_kind'] == 'push':
      comments_message = "\n".join([item['message']+"\n( "+item['url']+" )\n" for item in json_data['commits']])
      msg_tpl = """# %s 提交（%s）

WHAT'S NEW:

```
%s
```"""
      msg = msg_tpl % (json_data['user_name'], json_data['repository']['name'], comments_message)

    print(msg)
    send_message_to_robot(msg)
    return { "response":msg }

def hollo():
    # MPV, Based on bootstrap and jquery ad front-end
    return """
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>QUSEIT GITLAB WEBHOOK</title>

    <link href="//getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="//getbootstrap.com/docs/4.1/examples/sticky-footer/sticky-footer.css" rel="stylesheet">
  </head>

  <body>
    <main role="main" class="container" style='padding-top:20px'>
      <h3 class='text-center'>QUSEIT GITLAB WEBHOOK</h3>
      <p>It supports the following events</p>
      <ul>
        <li>PUSH EVENT</li>
      </ul>
    </main>

    <footer class="footer">
      <div class="container">
        <span class="text-muted">WEBVIEW TEST SUITES By QPYTHON</span>
      </div>
    </footer>

    <script src="//cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="//getbootstrap.com/docs/4.1/dist/js/bootstrap.min.js"></script>
    <script>
    $(document).ready(function(){
        //$('#btn_load').click(function(){
        //});
    </script>
  </body>
</html>
"""


######### WEBAPP ROUTERS ###############
app = Bottle()
app.route('/webhook/', method='POST')(webhook)
app.route('/', method='GET')(hollo)
app.route('/__exit', method=['GET','HEAD'])(__exit)
app.route('/assets/<filepath:path>', method='GET')(server_static)

app.route('/start/', method='POST')(run_start)

try:
    logger.info("START")
    server = MyWSGIRefServer(host="0.0.0.0", port=PORT)
    app.run(server=server,reloader=False)
except Exception as ex:
    errs = "Exception: %s" % repr(ex)
    logger.error(errs)
